package top.hongthorn.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.hongthorn.service.QiniuOSSService;
import top.hongthorn.util.DateUtils;

import java.util.Objects;
import java.util.UUID;


@Service
public class QiniuOSSServiceImpl implements QiniuOSSService {

    @Autowired
    private Auth auth;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Value("${OSS.path}")
    private String path;
    @Value("${OSS.documentName}")
    private String documentName;
    @Value("${file.allowed}")
    private String[] allowed;
    @Value("${OSS.bucketName}")
    private String bucketName;

    @Override
    public String uploadFile(MultipartFile file) throws RuntimeException {
        try {
            String originalFileName = Objects.requireNonNull(file.getOriginalFilename());
            if (!isFileAllowed(originalFileName)) throw new IllegalArgumentException();
            String fileName = getRandomImgName(originalFileName);
            byte[] uploadBytes = file.getBytes();
            String upToken = auth.uploadToken(bucketName);
            String key = documentName + DateUtils.getTodayDate() + "/" + fileName;
            uploadManager.put(uploadBytes, key, upToken);

            return key;
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("错误的文件名");
        } catch (Exception e) {
            System.out.println("message:" + e.getMessage());
            throw new RuntimeException("文件上传出错");
        }
    }

    @Override
    public Boolean deleteFile(String key) throws RuntimeException {
        if (Objects.isNull(checkFile(key))) {
            return true;
        } else {
            try {
                bucketManager.delete(bucketName, key);
                return true;
            } catch (QiniuException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    @Override
    public FileInfo checkFile(String key) {
        FileInfo fileInfo = null;
        try {
            fileInfo = bucketManager.stat(bucketName, key);
        } catch (QiniuException ignored) {
        }
        return fileInfo;
    }

    @Override
    public String getFileAskingPath(String filePath) {
        return path + "/" + filePath;
    }


    private static String getRandomImgName(String fileName) throws IllegalArgumentException {
        int index = fileName.lastIndexOf(".");

        if (fileName.isEmpty() || index == -1) {
            throw new IllegalArgumentException();
        }

        String suffix = fileName.substring(index).toLowerCase();

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        return uuid + suffix;
    }


    private boolean isFileAllowed(String fileName) {
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        for (String allow : allowed) {
            if (allow.equals(suffixName)) {
                return true;
            }
        }
        return false;
    }
}